package com.prs.crm.dao;

import java.io.Serializable;
import java.util.Date;

import org.apache.commons.beanutils.PropertyUtils;
import org.courser.Util;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import com.prs.crm.context.AppContext;
import com.prs.crm.domain.BaseEntity;

public class DefaultListener extends EmptyInterceptor{
	
	private static final long serialVersionUID = 1L;

		@Override
	   public boolean onSave(Object object,Serializable id,
               Object[] state,
               String[] propertyNames,
               Type[] types) {
		
		if (object instanceof BaseEntity)
		{
			BaseEntity entity = (BaseEntity)object;
			Date now = Util.nowFullTime();
		     for (int i = 0; i < propertyNames.length; i++) {   
		    	 if (propertyNames[i].equals("recordTime"))
		    	 {
		    		
		    		 if (entity.getRecordTime()==null)
		    		 {
		    			 ((BaseEntity)entity).setRecordTime(now);
		    			 state[i]=now;
		    		 }
		    	 }
		    	 if (propertyNames[i].equals("modifyTime"))
		    	 {
		    		 if (entity.getRecordTime()!=null)
		    		 {
		    			 ((BaseEntity)entity).setModifyTime(now);
		    			 state[i]=now;
		    		 }
		    	 } 
		    	 if (propertyNames[i].equals("recorder"))
		    	 {
		    		 if (entity.getRecorder()==null)
		    		 {
		    			 if (AppContext.getAccountContext()!=null
		    						&& AppContext.getAccountContext().currentUser()!=null)
		    				{
		    				 	((BaseEntity)entity).setRecorder(AppContext.getAccountContext().currentUser());
		    					state[i]=AppContext.getAccountContext().currentUser();
		    				}
		    		 }
		    	 } 
		      }
		}
	     return false;   
	}
}
